<template>
  <div>
    <el-upload
      ref="upload"
      class="upload-demo"
      action="http://localhost:8000/gu/excel/uploadExcel"
      :on-success="handleSuccess"
      :before-upload="beforeUpload"
      :file-list="fileList"
      :auto-upload="false"
      :headers="headers"
    >
      <el-button slot="trigger" size="small" type="primary">选择 Excel 文件</el-button>
      <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传</el-button>
      <div slot="tip" class="el-upload__tip">只能上传 Excel 文件，且不超过 5MB</div>
    </el-upload>
    <div v-if="uploadStatus" class="upload-status">{{ uploadStatus }}</div>
  </div>
</template>

<script>
import {getToken} from '@/utils/auth'

export default {
  data() {
    return {
      fileList: [], // 上传文件列表
      uploadStatus: '', // 上传状态
      headers: {
        Authorization: getToken(),
      },
    };
  },
  methods: {
    beforeUpload(file) {
      const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || file.type === 'application/vnd.ms-excel';
      const isLt5M = file.size / 1024 / 1024 < 5;

      if (!isExcel) {
        this.$message.error('上传文件只能是 Excel 格式!');
      }
      if (!isLt5M) {
        this.$message.error('上传文件大小不能超过 5MB!');
      }

      return isExcel && isLt5M;
    },
    submitUpload() {
      this.$refs.upload.submit(); // 手动触发上传
    },
    handleSuccess(response, file, fileList) {
      this.uploadStatus = '文件上传成功';
      // 处理上传成功后的逻辑
    },
    handleError(err, file, fileList) {
      this.uploadStatus = '文件上传失败: ' + err.message;
      // 处理上传失败后的逻辑
    },
  },
};
</script>

<style scoped>
.upload-demo {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.upload-status {
  margin-top: 10px;
  color: #999;
}
</style>
